import copy
import os
import uuid

from flask import request, jsonify, json, Blueprint

from app.kit.file import write_to_file
from app.kit.string import check_is_end, decode_if_needed
from app.routes.node import prompt_parser, text_2_image, call_node
from app.services.ai_service import call_ai_model, messages_session, ai_role_content

ai_bp = Blueprint('ai', __name__)


@ai_bp.route('/code/generate', methods=['GET'])
def generate():
    """代码生成
        - 接收输入
        - 大模型解析参数
        - 调用脚本生成
    :arg
        text
    :return:

    """
    text = request.args.get('text')
    if not text:
        return jsonify({
            "code": 400,
            "message": "请输入信息",
        }), 400

    messages_session.append({'role': "user", 'content': text})
    call_ai_resp = call_ai_model(messages_session)
    print("ai resp:", call_ai_resp)

    messages_session.append({'role': 'assistant', 'content': call_ai_resp})
    # 判断对话是否结束
    if check_is_end(call_ai_resp):
        msg = prompt_parser(call_ai_resp)
        arr = [
            {'role': 'system', 'content': 'You are a helpful assistant.'},
            {'role': "user", 'content': msg}
        ]
        resp = call_ai_model(arr)
        print("对话内容转json:", resp)

        # 处理返回加入包名 转成json字符串
        json_data = json.loads(resp)
        json_data['pkgName'] = str(uuid.uuid4()) + ".zip"
        json_data_tmp = copy.deepcopy(json_data)
        background = text_2_image(json_data['title'], json_data['desc'])
        json_data['background'] = background
        json_data_tmp['background'] = 'a.png'
        json_data_tmp['title'] = decode_if_needed(json_data_tmp['title'])
        json_data_tmp['desc'] = decode_if_needed(json_data_tmp['desc'])
        json_data_tmp['initData'] = decode_if_needed(json_data_tmp['initData'])
        json_string = json.dumps(json_data_tmp, ensure_ascii=False, indent=4)
        print("json str:", json_string)

        # 写入文件
        file_path = os.path.join("CardTemplate", "card.json")
        write_to_file(file_path, json_string)

        # 调用node
        call_node()

        status = "complete"
        file_name = json_data['pkgName']

        aiResp = '#### 已为您成功创建卡片，预览图如下：'
        # 重置上下文
        # reset_messages()
    else:
        status = "ongoing"
        file_name = ''
        json_data = []

    print("last response:", json_data)
    return jsonify({
        "code": 200,
        "file_name": file_name,
        "status": status,  # 进行中（回复话术）  完成（返回文件名）
        "image": "",
        "repay": call_ai_resp,
        "json_data": json_data
    })


def reset_messages():
    """重置 AI 对话上下文"""
    messages_session[:] = [{'role': 'system', 'content': ai_role_content}]
